package com.example.computer_exam_training_sys.service.impl;

import com.example.computer_exam_training_sys.entity.UserStudyPlan;
import com.example.computer_exam_training_sys.mapper.UserStudyPlanMapper;
import com.example.computer_exam_training_sys.service.UserStudyPlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserStudyPlanServiceImpl implements UserStudyPlanService {

    @Autowired
    private UserStudyPlanMapper planMapper;

    @Override
    public List<UserStudyPlan> getUserPlans(Long userId) {
        return planMapper.findByUserId(userId);
    }

    @Override
    @Transactional
    public int createPlan(UserStudyPlan plan) {
        return planMapper.insert(plan);
    }

    @Override
    @Transactional
    public int updatePlan(UserStudyPlan plan) {
        return planMapper.update(plan);
    }

    @Override
    @Transactional
    public int updatePlanProgress(Long planId, int progress) {
        UserStudyPlan plan = planMapper.findById(planId);
        if (plan == null) {
            return 0;
        }
        
        plan.setCurrentProgress(progress);
        
        // 更新状态
        if (progress >= 100) {
            plan.setStatus(2); // 已完成
        } else if (progress > 0) {
            plan.setStatus(1); // 进行中
        }
        
        return planMapper.updateProgress(planId, progress, plan.getStatus());
    }
    
    @Override
    @Transactional
    public int updatePlanProgressByCourse(Long userId, Long courseId, int progress) {
        // 查找与该课程相关的学习计划
        List<UserStudyPlan> plans = planMapper.findByUserIdAndCourseId(userId, courseId);
        int updatedCount = 0;
        
        for (UserStudyPlan plan : plans) {
            // 更新进度
            int result = updatePlanProgress(plan.getPlanId(), progress);
            if (result > 0) {
                updatedCount++;
            }
        }
        
        return updatedCount;
    }

    @Override
    @Transactional
    public int deletePlan(Long planId) {
        return planMapper.deleteById(planId);
    }
} 